﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace FastPoster.MainForms
{
    #region using
    using DevComponents.DotNetBar;
    using FastPoster.DataProviders.BUS;
    using FastPoster.Helpers;
    using System.Diagnostics;
    using FastPoster.MainClasses;
    using Amib.Threading;
    using System.Threading;
    using System.Threading.Tasks;
    #endregion

    public partial class FrmTestDienDan : Office2007Form
    {
        public List<Poster>     LstPoster { get; set; }
        private int             currPoster;
        private string          END = Environment.NewLine;
        private string          LoginFailed = string.Empty;
        private BackgroundWorker PostingBackgroundWorker;

        public FrmTestDienDan()
        {
            InitializeComponent();
            InitWorker();
        }

        private void btnDanhSachDienDan_Click(object sender, EventArgs e)
        {
            LoadDanhSachDienDan();

            // Init other controls
            progBarKetQuaDangTin.Minimum = 0;
            progBarKetQuaDangTin.Maximum = LstPoster.Count;
            progBarKetQuaDangTin.Step = 1;
            progBarKetQuaDangTin.Value = 0;
        }

        /// <summary>
        /// Init background worker
        /// </summary>
        private void InitWorker()
        {
            PostingBackgroundWorker = new BackgroundWorker();
            PostingBackgroundWorker.WorkerReportsProgress = true;
            PostingBackgroundWorker.WorkerSupportsCancellation = true;

            PostingBackgroundWorker.DoWork += PostingBackgroundWorker_DoWork;
            PostingBackgroundWorker.ProgressChanged += PostingBackgroundWorker_ProgressChanged;
            PostingBackgroundWorker.RunWorkerCompleted += PostingBackgroundWorker_RunWorkerCompleted;
        }

        public void DoTest(Poster poster, int index)
        {
            try
            {
                if (PostingBackgroundWorker.CancellationPending)
                {
                    return;
                }

                Task.Factory.StartNew(() => poster.TestForum(index));
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                {
                    GlobalVariables.Logger.Error("DoTest: failed - error: " + ex.InnerException.Message);
                }
                else
                {
                    GlobalVariables.Logger.Error("DoTest: failed - error: " + ex.Message);
                }
            }
        }

        /// <summary>
        /// This method is executed when RunWorkerAsync is called.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PostingBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            GlobalVariables.Logger.Info("Checking: started");
            try
            {
                for (int i = 0; i < LstPoster.Count; i++)
                {
                    Poster poster = (Poster)dtgvDanhSachDienDan.Rows[i].Cells[1].Value;
                    poster.LoginSuccess = true;
                    poster.ProgressChanged += OnPosterProgressChanged;

                    DoTest(poster, i);
                    Thread.Sleep(1000);
                }
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                {
                    GlobalVariables.Logger.Error("Checking: failed - error: " + ex.InnerException.Message);
                }
                else
                {
                    GlobalVariables.Logger.Error("Checking: failed - error: " + ex.Message);
                }
            }
        }

        private void PostingBackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            if (!PostingBackgroundWorker.CancellationPending)
            {
                progBarKetQuaDangTin.PerformStep();
            }
        }

        private void PostingBackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
        }

        public List<Poster> RetrieveForumList()
        {
            List<Poster> list = new List<Poster>();
            var objBus = new DienDanBUS(GlobalVariables.g_strPath);
            var ds = objBus.SelectAll();

            if (ds.Tables[0].Rows.Count > 0)
            {
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    var item = new Poster
                    {
                        Url = row["URL"].ToString(),
                        User = row["TenDangNhap"].ToString(),
                        Pass = row["MatKhau"].ToString(),
                    };
                    list.Add(item);
                }
            }

            return list;
        }

        public void LoadDanhSachDienDan()
        {
            LstPoster = RetrieveForumList();

            dtgvDanhSachDienDan.Rows.Clear();
            foreach (Poster poster in LstPoster)
            {
                object[] values = new object[3];
                values[0] = dtgvDanhSachDienDan.Rows.Count + 1;
                values[1] = poster;
                dtgvDanhSachDienDan.Rows.Add(values);
            }
        }

        private void btnTestDienDan_Click(object sender, EventArgs e)
        {
            if (dtgvDanhSachDienDan.Rows.Count <= 0)
            {
                MessageBoxEx.Show("Danh sách diễn đàn rỗng", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            
            currPoster = 0;
            progBarKetQuaDangTin.Value = 0;

            // Activate checking
            if (PostingBackgroundWorker.IsBusy)
            {
                PostingBackgroundWorker.CancelAsync();
            }
            else
            {
                progBarKetQuaDangTin.Value = progBarKetQuaDangTin.Minimum;
                PostingBackgroundWorker.RunWorkerAsync();
            }
        }

        private void OnPosterProgressChanged(object sender, EventArgs e)
        {
            var eventType = (ProgressChangedArgs)e;
            MethodInvoker method = null;
            if (base.InvokeRequired)
            {
                if (method == null)
                {
                    method = delegate
                    {
                        this.OnPosterProgressChanged(sender, e);
                    };
                }
                base.BeginInvoke(method);
            }
            else
            {
                Poster poster = (Poster)sender;
                this.dtgvDanhSachDienDan.Rows[(int)eventType.Index].Cells[2].Value = eventType.ProgressState;
                if (poster.PostFinish)
                {
                    if (!poster.LoginSuccess)
                    {
                        LoginFailed += poster.ResponseUrl + END;
                    }
                    currPoster++;
                    PostingBackgroundWorker.ReportProgress(currPoster >= LstPoster.Count ? 100 : (int)(currPoster / LstPoster.Count * 100));
                }
            }
        }

        public void XuatRaFile()
        {
            // Write the string to a file.
            System.IO.StreamWriter file = new System.IO.StreamWriter(Application.StartupPath + "\\Exports\\output.txt");
            file.WriteLine(LoginFailed);
            file.Close();
        }

        private void dtgvDanhSachDienDan_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (((e.RowIndex >= 0) && (dtgvDanhSachDienDan.Rows[e.RowIndex].Cells[e.ColumnIndex].Value != null)) && ((e.ColumnIndex == 1)))
            {
                Process.Start(dtgvDanhSachDienDan.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString());
            }
        }
    }
}
